<?php
/*
数据库连接
*/
function db_connect(){
	$link = @mysqli_connect('127.0.0.1','root','root','comsite1801');

	if ($link==false) {
		die('数据库暂时无法使用,请检查名称或密码等信息');
	}

	mysqli_query($link,'SET NAMES utf8');
	return $link;
}
/*
数据库查询
封装重复的代码，让不重复的变成参数
*/
function db_select($table,$field='*'){
	$link = db_connect();
	$sql = 'SELECT '.$field.' FROM `'.DB_PREFIX.$table.'` ORDER BY `id` DESC';

	$query = mysqli_query($link,$sql);

	// var_dump(mysqli_error($link));exit;
	if ($query==false) {
		echo 'sql语句有问题：'.$sql;
	}else{
		$rs=array();
		while ($row=mysqli_fetch_assoc($query)) {
			$rs[] = $row;
		}
		//var_dump($rs);exit;

	}
	return $rs;
}
/*
数据表查询一条
封装重复的代码，让不重复的变成参数
*/
function db_find($table,$where){
	$link = db_connect();
	$sql = 'SELECT * FROM `'.DB_PREFIX.$table.'` where '.$where;

	$query = mysqli_query($link,$sql);

	// var_dump(mysqli_error($link));exit;
	if ($query==false) {
		echo 'sql语句有问题：'.$sql;
	}else{
		$rs=array();
		$row=mysqli_fetch_assoc($query);

		//var_dump($rs);exit;

	}
	return $row;
}
/*
数据删除
封装重复的代码，让不重复的变成参数
*/
function db_del($table){
	$link=db_connect();
	
	$sql = 'delete from `'.DB_PREFIX.$table.'` where `id`='.$_GET['id']; 

	$query = mysqli_query($link,$sql);

	if ($query==true) {
		echo '<script>alert("删除成功");location.href="http://localhost/comsite1801/admin/'.$table.'_index.php"</script>';
	}else{
		echo '<script>alert("删除失败");location.href="http://localhost/comsite1801/admin/'.$table.'_index.php"</script>';
	}
}
/*
数据添加
封装重复的代码，让不重复的变成参数
*/
function db_add($table){
	$link=db_connect();
	$keyStr='';
	$valueStr='';
	foreach($_POST as $k=>$val){
		$keyStr=$keyStr.'`'.$k.'`,';
		$valueStr=$valueStr.'"'.$val.'",';
	}
	$keyStr=substr($keyStr,0,-1);
	$valueStr=substr($valueStr,0,-1);
	$sql = 'INSERT INTO `'.DB_PREFIX.$table.'`('.$keyStr.') values('.$valueStr.')';
	$query=mysqli_query($link,$sql);
	
	// var_dump(mysqli_query($link,$sql));exit;
	
	if ($query==true){
		echo '<script>alert("添加成功");location.href="http://localhost/comsite1801/admin/'.$table.'_index.php";</script>';
	}else{
		echo '<script>alert("添加失败");location.href="http://localhost/comsite1801/admin/'.$table.'_add.php";</script>';
	}
}
/*
数据更新
封装重复的代码，让不重复的变成参数
*/
function db_update($table){
	$link=db_connect();
	
	$updateStr='';
	foreach($_POST as $k=>$val){
		$updateStr=$updateStr.'`'.$k.'`="'.$val.'",';
	}
	$updateStr=substr($updateStr,0,-1);
	$sql = 'update `'.DB_PREFIX.$table.'` set '.$updateStr.' where `id`='.$_POST['id'];
	$query = mysqli_query($link,$sql);
		
	//var_dump(mysqli_query($link,$sql));exit;
		
	if ($query == true){
		echo '<script>alert("更新成功");location.href="http://localhost/comsite1801/admin/'.$table.'_index.php";</script>';
		exit;
	}else{
		echo '<script>alert("更新失败");location.href="http://localhost/comsite1801/admin/'.$table.'_update.php";</script>';
		exit;
	}
}


